/**
 * 
 */
package com.wubo.sec.web.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.wubo.common.date.DateUtil;
import com.wubo.common.util.ObjectUtils;
import com.wubo.common.util.StringUtils;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.UserData;
import com.wubo.sec.core.UserOnlineManager;
import com.wubo.sec.filter.UserBeforeFilter;
import com.wubo.sec.model.User;
import com.wubo.sec.service.IUserService;

import flexjson.JSONSerializer;

/**
 * @author wubo
 * @CreateDate 2010-8-5
 * @version 1.0.01
 */
@Controller
public class UserMgtAction extends BaseSecAction {
	@Autowired
	private IUserService userService;
	@Autowired
	private UserOnlineManager userOnlineManager;
	@Autowired
	private UserBeforeFilter userBeforeFilter;
	
	public static String INIT_PWD = "123456";
	
	private List<User> users;
	
	private String username;
	
	private String startDate;
	
	private String endDate;
	
	private String orderby;
	
	private String active;
	
	private String locked;

	private UserData currentUser;

	private User user;

	private String id;
	
	private String isLock;

	private String newpwd;

	public String checkName(){
		if(user != null && StringUtils.isEmpty(user.getUsername())){
			jsonSuccess(false);
		}else{
			boolean isExist = userService.isExist(user.getUsername());
			logger.info("Username : ["+username+"] IS Exist:"+isExist);
			jsonSuccess(! isExist);
		}
		return null;
	}
	
	public String resetPassword(){
		try{
			User user = userService.get(id);
			if(StringUtils.isEmpty(newpwd)){
				newpwd = INIT_PWD;
			}
			userService.onPasswordChange(user, newpwd);
			jsonSuccess(null);
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
		return null;
	}

	public String add() {
		try{
			if(logger.isDebugEnabled()){
				logger.debug("AddUser:"+ObjectUtils.objToString( user) );
			}
			if( StringUtils.isEmpty(user.getPassword()) )
				user.setPassword(INIT_PWD);
			user.setOwner( SecurityManager.getCurrentUser().getUsername() );
			
			if(user.getExpiredDate() != null){
				date2MidNight(user.getExpiredDate());
			}
			
			userService.create(user);
			
			jsonSuccess(null);
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
		return null;
	}
	
	public String edit() {
		try{
			if(logger.isDebugEnabled()){
				logger.debug("UpdateUser:"+ObjectUtils.objToString( user) );
			}
			
			if(user.getExpiredDate() != null){
				date2MidNight(user.getExpiredDate());
			}
			
			userService.update(user);
			
			jsonSuccess(null);
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
		return null;
	}
	
	public String lock() throws Exception {
		if(! StringUtils.isEmpty(id) )
			userService.lock(id.split(","), Boolean.parseBoolean(isLock));
		
		list();
		
		flag = true;
		
		return SUCCESS;
	}
	
	public String del() throws Exception {
		if(! StringUtils.isEmpty(id) ){
			String[] usernames = id.split(",");
			for(String username: usernames){
				userService.delete(userService.getByUsername(username));
			}
		}
		list();
		
		flag = true;
		
		return SUCCESS;
	}
	
	private String q; //用于AutoComplete
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	public void autoComplete() {
		try{
			List<String[]> usernames = userService.listUsername(q);
			json(new JSONSerializer().serialize(usernames));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
	}

	public String list() throws Exception {
		StringBuilder where = new StringBuilder("where 1=1");

		if(! StringUtils.isEmpty(username)){
			where.append( " and ( u.username like '%"+username+"%' or u.truename like '%"+username+"%' or u.nickname like '%"+username+"%')" );
		}
		if(!StringUtils.isEmpty(active)){
			if(!active.trim().equals("2")){
				where.append(" and u.active ="+active);
			}
		}
		if(!StringUtils.isEmpty(locked)){
			if(!locked.trim().equals("2")){
				where.append(" and locked ="+locked);
			}
		}
		where.append(userBeforeFilter.sift());
		
		List<Date> params = new ArrayList<Date>(2);
		if(! StringUtils.isEmpty(startDate)){
			params.add(DateUtil.StringToDate(startDate));
			where.append(" and u.createTime >= ?");
		}
		if(! StringUtils.isEmpty(endDate)){
			params.add(DateUtil.StringToDate(endDate+" 23:59:59"));
			where.append(" and u.createTime <= ?");
		}
		if(StringUtils.isEmpty(orderby)){
			orderby = " order by u.createTime desc";
		}
		
		Object[] args = params.toArray();
		
		total = userService.getTotal(where.toString(), args);
		
		where.append(orderby);
		
		if(limit == -1){
			users = userService.find(where.toString(), args);
		}else{
			users = userService.getSplitPage(start, limit>0?limit:20, where.toString(), args);
		}
		return SUCCESS;
	}
	
	public String listForAssign(){
		StringBuilder where = new StringBuilder("where 1=1");

		if(! StringUtils.isEmpty(username)){
			where.append( " and ( u.username like '%"+username+"%' or u.truename like '%"+username+"%' or u.nickname like '%"+username+"%')" );
		}
		
		where.append(userBeforeFilter.sift());
		
		users = userService.findRunAs(where.toString(), null);
		
		String result = ServletActionContext.getRequest().getParameter("result");
		if(StringUtils.hasText(result)){
			return result;
		}
		return "radio";
	}
	
	/* 为日期加上时间 23:59:59 
	 * @param date
	 * @throws ParseException
	 */
	private void date2MidNight(Date date) throws ParseException {
		String datestr = DateUtil.DateToYMD(date);
		date = DateUtil.StringToDate(datestr+" 23:59:59");
	}
	
	public String listOnline(){
		try{
			jsonSuccess(new JSONSerializer().serialize(userOnlineManager.getOnlineUsers()));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
		return null;
	}
	/*
	 * 得到当前用户
	 */
	public void getCurrent(){
		currentUser =  SecurityManager.getCurrentUser();
		super.jsonSuccess(new JSONSerializer().serialize(currentUser), true);
	}
	
	public String getActive() {
		return active;
	}

	public void setActive(String active) {
		this.active = active;
	}

	public String getLocked() {
		return locked;
	}

	public void setLocked(String locked) {
		this.locked = locked;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public UserOnlineManager getUserOnlineManager() {
		return userOnlineManager;
	}

	public void setUserOnlineManager(UserOnlineManager userOnlineManager) {
		this.userOnlineManager = userOnlineManager;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getOrderby() {
		return orderby;
	}

	public void setOrderby(String orderby) {
		this.orderby = orderby;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public String getIsLock() {
		return isLock;
	}

	public void setIsLock(String isLock) {
		this.isLock = isLock;
	}

	public String getNewpwd() {
		return newpwd;
	}

	public void setNewpwd(String newpwd) {
		this.newpwd = newpwd;
	}

	public void setCurrentUser(UserData currentUser) {
		this.currentUser = currentUser;
	}

	public UserBeforeFilter getUserBeforeFilter() {
		return userBeforeFilter;
	}

	public void setUserBeforeFilter(UserBeforeFilter userBeforeFilter) {
		this.userBeforeFilter = userBeforeFilter;
	}
	
}
